 package com.solution.pc.order.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.solution.admin.company.entity.SysPayConfigEntity;
import com.solution.admin.company.service.SysPayConfigService;
import com.solution.admin.customer.entity.CompanyEntity;
import com.solution.admin.customer.entity.CompanyExpressConfigEntity;
import com.solution.admin.customer.entity.CustomerEntity;
import com.solution.admin.customer.entity.DeliveryAddressEntity;
import com.solution.admin.customer.service.CompanyExpressConfigService;
import com.solution.admin.customer.service.CompanyService;
import com.solution.admin.customer.service.CustomerService;
import com.solution.admin.customer.service.DeliveryAddressService;
import com.solution.admin.order.constants.OrderConstants;
import com.solution.admin.order.constants.OrderConstants.ORDER_PAY_MODEL;
import com.solution.admin.order.entity.OrderContractEntity;
import com.solution.admin.order.entity.OrderDeliveredBillEntity;
import com.solution.admin.order.entity.OrderDetailEntity;
import com.solution.admin.order.entity.OrderEntity;
import com.solution.admin.order.entity.OrderInvoiceEntity;
import com.solution.admin.order.entity.OrderLogEntity;
import com.solution.admin.order.entity.OrderPayEntity;
import com.solution.admin.order.entity.OrderProductDeliveredEntity;
import com.solution.admin.order.service.OrderContractService;
import com.solution.admin.order.service.OrderDeliveredBillService;
import com.solution.admin.order.service.OrderInvoiceService;
import com.solution.admin.order.service.OrderLogService;
import com.solution.admin.order.service.OrderService;
import com.solution.admin.product.entity.ProductEntity;
import com.solution.admin.product.entity.ProductSpecEntity;
import com.solution.admin.product.service.ProductService;
import com.solution.admin.promotion.entity.PromotionProductEntity;
import com.solution.admin.settings.entity.KeyMapEntity;
import com.solution.admin.settings.service.KeyMapService;
import com.solution.common.constants.PublicStatus;
import com.solution.common.controller.BaseController;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.DateUtils;
import com.solution.common.utils.NumberToCN;
import com.solution.common.utils.string.StringUtil;
import com.solution.pc.order.entity.CustomerOrderStatisticsEntity;
import com.solution.pc.promotion.PromotionCheckUtil;
import com.solution.pc.shoppingcart.entity.ShoppingCartEntity;
import com.solution.pc.shoppingcart.service.ShoppingCartService;

/**
 * PC订单信息web控制层
 * @author lilp
 * @date 2017-09-14 23:35:39
 */
@RequestMapping("/pc/order")
@Controller
public class PcOrderController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(PcOrderController.class);

	@Autowired
	private OrderService orderService;
	
	@Autowired
	private ShoppingCartService shoppingCartService;
	
	@Autowired
	private DeliveryAddressService deliveryAddressService;
	
	@Autowired
	private PromotionCheckUtil promotionCheckUtil;
	
	@Autowired
	private SysPayConfigService sysPayConfigService;
	
	@Autowired
	private OrderDeliveredBillService orderDeliveredBillService;
	
	@Autowired
	private OrderContractService orderContractService;
	
	@Autowired
	private ProductService  productService;
	
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private OrderInvoiceService orderInvoiceService;
	
	@Autowired
	private KeyMapService keyMapService;

	@Autowired
	private OrderLogService orderLogService;

	@Autowired
	private CompanyService companyService;
	
	@Autowired
	private CompanyExpressConfigService companyExpressConfigService;
	
	
	/**
	 * 分页查询我的订单
	 * @param order 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/list")
	public String listOrderPage(HttpServletRequest request){
//		String tmpPage = request.getParameter("page");
//		String tmpRows = request.getParameter("rows");
//		int pageNum= 1;
//		if(StringUtil.isNotEmpty(tmpPage)){
//			pageNum=Integer.parseInt(request.getParameter("page").toString());
//		}
//		int numPerPage= 10;
//		if(StringUtil.isNotEmpty(tmpRows)){
//			numPerPage=Integer.parseInt(request.getParameter("rows").toString());
//		}
		PageParam pageParam = super.getPageParam(request);
//		pageParam.setPageNum(pageNum);
//		pageParam.setNumPerPage(numPerPage);
		// 查询字符串
		String searchKey = request.getParameter("searchKey");
		// 订单状态
		String orderStatus = request.getParameter("orderStatus");
		// 付款模式 (货到付款+未付款=欠款)
		String payModel =request.getParameter("payModel");
		// 付款状态
		String payStatus = request.getParameter("payStatus");
		// 是否延期
		String isOver = request.getParameter("isOver");
		
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("searchKey", searchKey);
		paramMap.put("orderStatus", orderStatus);
		paramMap.put("customerId", getCustomerId());
		paramMap.put("payModel", payModel);
		paramMap.put("payStatus", payStatus);
		paramMap.put("isOver", isOver);
		
		try {
			PageBean pageBean = orderService.listMyOrderPage(pageParam, paramMap);
			List<Object> orderList = pageBean.getRecordList();
			// 处理商品详情数据的转化
			if(orderList != null && orderList.size() > 0){
				for (Object object : orderList) {
					OrderEntity order = (OrderEntity)object;
					String productDetail = order.getProductDetail();
					if(StringUtil.isNotEmpty(productDetail)){
						// 将商品详情json串转化为 OrderDetailEntity 列表
						String productDetailJsonStr = "["+productDetail+"]";
						List<OrderDetailEntity> orderDetailList = JSONArray.parseArray(productDetailJsonStr, OrderDetailEntity.class);
						// 如果是部分发货，前台用户也可以进行签收
						if(orderDetailList != null && orderDetailList.size() > 0){
							for (OrderDetailEntity detail : orderDetailList) {
								if(detail.getSendNum() > 0){
									order.setShowSign("true");
								}
								if(StringUtil.isNotEmpty(detail.getProductSpec())){
									List<ProductSpecEntity> productSpecList = JSONArray.parseArray(detail.getProductSpec(), ProductSpecEntity.class);;
									detail.setProductSpecList(productSpecList);
								}
							}
						}
						order.setProductList(orderDetailList);
					}
				}
			}
			request.setAttribute("orderList", pageBean.getRecordList());
			request.setAttribute("pageBean", pageBean);
			request.setAttribute("searchKey", searchKey);
			request.setAttribute("orderStatus", orderStatus);
			request.setAttribute("payModel", payModel);
			request.setAttribute("payStatus", payStatus);
			request.setAttribute("isOver", isOver);

			// 查询订单取消原因
			List<KeyMapEntity>  cancelReasonList = keyMapService.listKeyMap("orderCancelReason");
			request.setAttribute("cancelReasonList", cancelReasonList);
			// 左侧我的菜单【我的订单】高亮显示
			request.setAttribute("page", "order");
			
		} catch (Exception e) {
			handleException("分页查询订单信息失败", logger, e);
		}
		return "/pc/my/order_list";
	}
	
	/**
	 * 查询个人订单中，待付款和欠款订单数量，在我的订单页面显示订单数据小徽标
	 * @param request 请求对象
	 * @return
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/listOrderStatusCount")
	@ResponseBody
	public Map<String, Object> listOrderStatusCount(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			// 先获取订单其他数量
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("customerId", getCustomerId());
			OrderEntity orderCount = orderService.listOrderStatusCount(param);
			try {
				// 逾期数量
				param.put("curWeekStartTime", DateUtils.getCurWeek());
				param.put("curMonthStartTime", DateUtils.getCurMonth());
				param.put("companyId", getCompany().getId());
				List<CustomerOrderStatisticsEntity> cosList = orderService.listCustomerOrderStatistics(param);
				Map<String, String> tmpMap = new HashMap<String, String>();
				if (cosList != null && cosList.size() > 0) {
					for (CustomerOrderStatisticsEntity order : cosList) {
						tmpMap.put(order.getOrderStatus(), order.getOrderNum());
					}
				}
				String overduedNum = tmpMap.get("OVERDUED_NUM");
				Double overDoubleNumber = Double.parseDouble(StringUtil.isNotEmpty(overduedNum) ? overduedNum : "0");
				orderCount.setOverDuedCount(overDoubleNumber.intValue());
			} catch (Exception e) {
				e.printStackTrace();
			}
			resultMap.put("orderCount", orderCount);
			resultMap.put(PublicStatus.RESULT_CODE, 1);
			resultMap.put(PublicStatus.RESULT_MSG, "操作成功");
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			handleException("查询个人订单状态统计数量", logger, e);
		}
		return resultMap;
	}
	
	
	
	/**
	 * 分页查询我的订单
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/detail")
	public String toOrderDetail(HttpServletRequest request){
		// 订单编号
		String orderCode = request.getParameter("orderCode");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("orderCode", orderCode);
		try {
			// 查询单条订单
			List<OrderEntity> orderList = orderService.listOrder(paramMap);
			BigDecimal totalProductMoneyAfterAdjust = new BigDecimal(0);
			if (orderList != null && orderList.size() > 0) {
				OrderEntity order = orderList.get(0);
				if (StringUtil.isNotEmpty(order.getProductDetail())) {
					List<OrderDetailEntity> productList = JSONArray.parseArray("[" + order.getProductDetail() + "]",OrderDetailEntity.class);
					if (productList != null && productList.size() > 0) {
						for (OrderDetailEntity product : productList) {
							// 累计商品总金额 如果有商品调价，则按调价后价格，否则按商品原价
							product.setProductItemMoney(product.getProductAdjustPrice().multiply(new BigDecimal(product.getBuyNum())));
							totalProductMoneyAfterAdjust = totalProductMoneyAfterAdjust.add(product.getProductItemMoney());
							if(StringUtil.isNotEmpty(product.getProductSpec())){
								List<ProductSpecEntity> productSpecList = JSONArray.parseArray(product.getProductSpec(), ProductSpecEntity.class);;
								product.setProductSpecList(productSpecList);
							}
						}
					}
					request.setAttribute("productList", productList);
					request.setAttribute("totalProductMoneyAfterAdjust", totalProductMoneyAfterAdjust);
				}
				request.setAttribute("order", order);
				// 查询发票信息
				List<OrderInvoiceEntity>  invoiceList = orderInvoiceService.listOrderInvoice(paramMap);
				if(invoiceList != null && invoiceList.size() > 0){
					request.setAttribute("invoice", invoiceList.get(0));
				}
				
				// 查询已发货的商品清单
				List<OrderDeliveredBillEntity> deliveredList = orderDeliveredBillService.listOrderDeliveredBill(paramMap);
				request.setAttribute("deliveredList", deliveredList);
			}
		} catch (Exception e) {
			handleException("查询我订单详情页面", logger, e);
		}
		return "/pc/my/order_detail";
	}
	
	
	/**
	 * 提交订单
	 * @param request 请求对象
	 * @param orderEntity 订单信息实体
	 * @return
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/commitOrder")
	@ResponseBody
	public Map<String, Object> commitOrder(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		Map<String, Object> param = new HashMap<String, Object>();
		// 配送地址
		param.put("deliveryAddressId", request.getParameter("deliveryId"));
		param.put("shoppingcartIds", request.getParameter("shoppingcartIds"));
		param.put("payModel", request.getParameter("payModel"));
		param.put("deliveryType", request.getParameter("deliveryType"));
		param.put("invoiceType", request.getParameter("invoiceType"));
		param.put("invoiceId", request.getParameter("invoiceId"));
		param.put("points", request.getParameter("points"));
		param.put("modifier", getCurrentUserCodeWithAnonymous(request));
		
		
		// 保存订单信息
		// 【1】、生成订单编码 及 订单基本信息
		OrderEntity order = new OrderEntity();
		String currentUserCode = getCurrentUserCodeWithAnonymous(request).toLowerCase();
		// 订单编号   1位下单渠道+时间戳后8位+用户登录名后4位
		String orderCode = OrderConstants.ORDER_CHANNEL.PC.getCode()
				+String.valueOf(System.currentTimeMillis()).substring(3)
				+currentUserCode.substring(currentUserCode.length()-4);
		order.setOrderCode(orderCode);
		
		// 根据当前用户code查询客户及公司基本信息
		CompanyEntity company = getCompany();
		CustomerEntity customer = getCustomer();
		order.setCustomerId(getCustomerId());
		order.setCustomerCompanyId(company.getId());
		order.setCustomerCompanyName(company.getCompanyName());
		order.setCustomerName(customer.getUserName());
		order.setCustomerMobile(customer.getMobile());

		
		// 【2】重新计算订单价格
		// 订单金额、实付金额、积分折扣（消费积分、抵扣金额）、优惠券折扣、活动（满减）折扣、运费、调价、商品调价
		// 查询购物车结算商品->计算商品金额->计算活动->计算积分折扣->计算优惠券折扣
		// 【2-1】查询购物车金额
		List<String> shoppingcartIds = new ArrayList<String>();
		String itemIds = request.getParameter("shoppingcartIds");
		if(StringUtil.isNotEmpty(itemIds)){
			for (String id : itemIds.split(",")) {
				shoppingcartIds.add(id);
			}
		}
		param.put("shoppingcartIds", shoppingcartIds);
		// 临时存放订单详情列表
		List<OrderDetailEntity> orderDetailList = new ArrayList<OrderDetailEntity>();
		// 查询购物车结算的商品，形成订单详情记录
		List<ShoppingCartEntity> cartList = shoppingCartService.listShoppingCart(param);
		
		
		// 【2-2】积分折扣金额,设置消费积分及积分抵扣金额
		String points = request.getParameter("points");
		// 积分换算比例 ,暂时设为
		BigDecimal pointsRatio = OrderConstants.POINT_TO_MONEY_EXCHANGE_RATIO;
		BigDecimal pointsMoney = new BigDecimal(points).multiply(pointsRatio);
		// 积分抵扣金额
		order.setPointsMoney(pointsMoney);
		order.setUserPoints(new BigDecimal(points));
		
		// 【2-3】优惠券折扣
		String couponMoney =request.getParameter("couponMoney");
		order.setCouponMoney(new BigDecimal(couponMoney));
		// 使用优惠券的id
		String couponIds = request.getParameter("couponIds");
		order.setCouponIds(couponIds);
		
		// 【2-4】活动折扣
		// 用于根据商品编码product_code批量查询是否有参加活动
		List<String> productCodeList = new ArrayList<String>();
		for (ShoppingCartEntity sce : cartList) {
			// 提取商品product_code 字段
			productCodeList.add(sce.getProductCode());
		}
		// 重新计算商品活动折扣
		promotionCheckUtil.checkPromotion(cartList, productCodeList, getCustomerId());
		// 循环取出活动的结果 
		// 满赠 ： 赠品列表  赠送积分列表  赠送优惠券列表
		// 满减： 满减少金额
		// 满折：折扣
		
		// 订单总体折扣金额
		BigDecimal totalDiscountMoney = new BigDecimal(0);
		// 订单总体满减金额
		BigDecimal totalReduceMoney = new BigDecimal(0);
		
		for (ShoppingCartEntity item : cartList) {
			// 存储所有订单参加过的活动放 promotionInfo 字段
			List<PromotionProductEntity>  allPromotionList = new ArrayList<PromotionProductEntity>();
			// 单个商品购买金额
			BigDecimal cartItemMoney = item.getProductPrice().multiply(new BigDecimal(item.getBuyNum()));
			// 满减记录
			List<PromotionProductEntity>  reduceList = item.getReduceList();
			if(reduceList != null && reduceList.size() > 0){
				allPromotionList.addAll(reduceList);
				for (PromotionProductEntity reduce : reduceList) {
					totalReduceMoney = totalReduceMoney.add(reduce.getReduceMoney());
				}
			}
			// 满赠记录
			List<PromotionProductEntity>  giftList = item.getGiftList();
			if(giftList != null && giftList.size() > 0){
				allPromotionList.addAll(giftList);
			}
			// 满折记录
			List<PromotionProductEntity>  discountList = item.getDiscountList();
			if(discountList != null && discountList.size() > 0){
				allPromotionList.addAll(discountList);
				for (PromotionProductEntity discount : discountList) {
					// (1-(折扣数字/10)) * 购买金额
					totalDiscountMoney = totalDiscountMoney.add(
							(new BigDecimal(1).subtract(discount.getDiscount().divide(new BigDecimal(10)))).multiply(cartItemMoney));
				}
			}
			if(allPromotionList.size() > 0){
				item.setPromotionInfo(JSONArray.toJSONString(allPromotionList));
			}
		}
		
		
		
		// 订单折扣金额  = 满减金额 + 满折金额
		BigDecimal totalDiscount =  totalDiscountMoney.add(totalReduceMoney);
		order.setPromotionDiscountMoney(totalDiscount);
		// 总商品金额
		BigDecimal totalProductMoney = new BigDecimal(0);
		for (ShoppingCartEntity sce : cartList) {
			totalProductMoney = totalProductMoney.add(sce.getProductPrice().multiply(new BigDecimal(sce.getBuyNum())));
			OrderDetailEntity detail = new OrderDetailEntity();
			detail.setOrderCode(orderCode);
			detail.setProductId(sce.getProductId());
			detail.setProductCode(sce.getProductCode());
			detail.setProductName(sce.getProductName());
			// 商品规格
			detail.setProductSpec(sce.getProductSpec());
			detail.setProductPrice(sce.getProductPrice());
			// 参加活动的信息
			detail.setPromotionInfo(sce.getPromotionDesc());
			// 活动具体结果
			List<PromotionProductEntity> promotionResultList = new ArrayList<PromotionProductEntity>();
			// 满减+满赠+满折列表 => promotionResult
			if(sce.getReduceList() != null){
				promotionResultList.addAll(sce.getReduceList());
			}
			if(sce.getGiftList() != null){
				promotionResultList.addAll(sce.getGiftList());
			}
			if(sce.getDiscountList() != null){
				promotionResultList.addAll(sce.getDiscountList());
			}
			detail.setPromotionResult(JSONArray.toJSONString(promotionResultList));
			// 调价直接写成商品价格
			detail.setProductAdjustPrice(detail.getProductPrice());
			detail.setBuyNum(sce.getBuyNum());
			detail.setImagePath(sce.getImagePath());
			
			// 商品赠送积分系数
			detail.setProductPointRatio(sce.getProductPointRatio());
			// 客户系数
			detail.setCustomerPointRatio(getCompany().getCustomerFactor());
			// 商品最大折扣积分系数(在订单中暂时无用)
			detail.setExchangePointRatio(sce.getExchangePointRatio());
			// 商品模拟成本 
			detail.setProductSimulatePrice(sce.getProductSimulatePrice());
			orderDetailList.add(detail);
			
			// 提取商品product_code 字段
			productCodeList.add(sce.getProductCode());
		}
		// 商品类型（即：订单金额）
		order.setOrderMoney(totalProductMoney);
		// 订单中商品金额合计
		order.setTotalProductMoney(totalProductMoney);
		
		
		// 【2-5】运费 
		// 配送方式
		String deliveryType = request.getParameter("deliveryType");
		String deliveryFeePayType = request.getParameter("deliveryFeePayType");
		order.setDeliveryType(deliveryType);
		// 运费支付方式
		order.setDeliveryFeePayType(deliveryFeePayType);
		order.setDeliveryFeeMoney(new BigDecimal(0));
		
		// 后台重新计算运费,不能使用前台计算的运费
		String deliveryAddressId = request.getParameter("deliveryAddressId");
		BigDecimal orderDeliveryFee = calucateDelvieryFee(shoppingcartIds, deliveryAddressId, deliveryType, deliveryFeePayType);
		order.setDeliveryFeeMoney(orderDeliveryFee);
		
		// 【2-6】订单实付 (商品金额-积分抵扣-优惠券抵扣-活动抵扣-运费-订单调价)
		order.setAdjustOrderMoney(new BigDecimal(0));
		order.setAdjustProductMoney(new BigDecimal(0));
		BigDecimal realPayMoney = order.getOrderMoney().subtract(order.getCouponMoney())
				.subtract(order.getPointsMoney()).subtract(order.getPromotionDiscountMoney())
				.add(order.getDeliveryFeeMoney()).subtract(order.getAdjustOrderMoney());
		order.setRealPayMoney(realPayMoney);
		
		// 【3】订单类型、订单状态、调价标识、删除标记、创建人
		String payModel = request.getParameter("payModel");
		if(OrderConstants.ORDER_PAY_MODEL.PAY_NOW.getCode().equals(payModel)){
			// 立即付款，初始订单状态为待支付
			order.setOrderStatus(OrderConstants.ORDER_STATUS.WAIT_TO_PAY.getCode());
		}else if(OrderConstants.ORDER_PAY_MODEL.PAY_DELIVERY.getCode().equals(payModel)){
			// 货到付款，初始订单状态为待上传合同
			order.setOrderStatus(OrderConstants.ORDER_STATUS.WAIT_TO_UPLOAD_CONTRACT.getCode());
		}
		order.setAdjustPriceFlag("1");
		order.setOrderType(OrderConstants.ORDER_CHANNEL.PC.getCode());
		order.setIsDelete(PublicStatus.IS_DELETE.NORMAL.getId());
		order.setCreater(getUserCode());
		order.setIntro(request.getParameter("intro"));
		order.setDeliveryIntro(request.getParameter("deliveryIntro"));
		
		/**
		// 如果是立即支付 + 普通物流 + 运费立即付款 ==》 调价
		// 如果是立即支付 + 快递物流 + 运费立即付款 ==》 调价
		// 如果是货到付款 + 普通/快递 +运费只能到付
		// 如果是立即支付/货到付款 + 自提、其它 + 运费默认值为货到付款
		boolean redirectAdjust = false;
		// 立即支付
		if (OrderConstants.ORDER_PAY_MODEL.PAY_NOW.getCode().equals(payModel)) {
			if ("1".equals(order.getDeliveryType()) || "2".equals(deliveryType)) {
				// 普通 / 快递
				if ("01".equals(deliveryFeePayType)) {
					// 立即支付,跳转调价提示页面
					redirectAdjust = true;
				} else {
					redirectAdjust = false;
				}
			} else if ("0".equals(deliveryType) || "4".equals(deliveryType)) {
				// 自提 / 其它
				redirectAdjust = false;
			}
		} else {
			// 货到付款,运费只能到付
			redirectAdjust = false;
		}
		// 1 无需要调价  2 待调价(运费) 3 已调价 
		if(redirectAdjust){
			order.setAdjustPriceFlag("2");
		}
		*/
		
		// 【4】支付模式、支付方式、运费支付方式、配送类型
		order.setPayModel(request.getParameter("payModel"));
		order.setPayType(request.getParameter("payType"));
		order.setDeliveryFeePayType(request.getParameter("deliveryFeePayType"));
		order.setDeliveryType(request.getParameter("deliveryType"));
		
		// 【5】收货人姓名、联系方式、省市区街道、详细地址
		DeliveryAddressEntity address = deliveryAddressService.getDeliveryAddressById(Long.parseLong(deliveryAddressId));
		order.setProvinceCode(address.getProvinceCode());
		order.setProvinceName(address.getProvinceName());
		order.setCityCode(address.getCityCode());
		order.setCityName(address.getCityName());
		order.setAreaCode(address.getAreaCode());
		order.setAreaName(address.getAreaName());
		order.setStreetCode(address.getStreetCode());
		order.setStreetName(address.getStreetName());
		order.setAddress(address.getAddress());
		order.setReceiverName(address.getReceiverName());
		order.setReceiverMobile(address.getMobile());
		
		order.setDeliveryInfo("");
		
		
		// 【6】发票类型
		String invoiceType = request.getParameter("invoiceType");
		order.setInvoiceType(invoiceType);
		// 增值赋发票信息
		OrderInvoiceEntity invoice = new OrderInvoiceEntity();
		invoice.setOrderCode(orderCode);
		invoice.setCompnayName(request.getParameter("companyName"));
		invoice.setTaxNo(request.getParameter("taxNo"));
		invoice.setRegisteAddress(request.getParameter("registeAddress"));
		invoice.setRegistePhone(request.getParameter("registePhone"));
		invoice.setOpenBankName(request.getParameter("openBankName"));
		invoice.setBankAccount(request.getParameter("bankAccount"));
		
		// 【7】业务员代码、业务中姓名(需要实时)
		Map<String, Object> userMap = companyService.getSalesmanByCompanyId(getCompanyId());
		order.setSalesmanCode(userMap.containsKey("salesmanCode") ? userMap.get("salesmanCode").toString() : "--");
		// 获取业务员姓名
		order.setSalesmanName(userMap.containsKey("salesmanName") ? userMap.get("salesmanName").toString() : "--");
		// 订单基本信息
		param.put("orderInfo", order);
		// 要结算的商品
		param.put("orderDetailList", orderDetailList);
		// 发票
		param.put("invoice", invoice);
		
		try {
			//记录日志
			OrderLogEntity orderLog = new OrderLogEntity();
			orderLog.setOrderCode(order.getOrderCode());
			orderLog.setOperaterCode(getUserCode());
			orderLog.setOperaterName(getUserName());
			orderLog.setOpTime(new Date());
//			orderLog.setLogType(logType);
			orderLog.setLogContent("提交订单成功");
			orderLog.setCreater(getUserName());
			param.put("orderLogEntity", orderLog);
			
			result = orderService.commitOrder(param);
			resultMap.put("orderCode", orderCode);
			resultMap.put("payModel", order.getPayModel());
			resultMap.put("deliveryAddress", address.getProvinceName()+address.getCityName()+address.getAreaName()+address.getStreetName());
			resultMap.put("receiverName", address.getReceiverName());
			resultMap.put("receiverMobile", order.getReceiverMobile());
			resultMap.put("realPayMoney", order.getRealPayMoney());
			// = 2 跳转调价页面，提示正在调整运费
			resultMap.put("redirectAdjust", order.getAdjustPriceFlag());
			resultMap.put(PublicStatus.RESULT_CODE, result>0?"1":"0");
			resultMap.put(PublicStatus.RESULT_MSG, result>0?"操作成功":"操作失败");
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			handleException("提交订单失败", logger, e);
		}
		return resultMap;
	}
	
	
	/**
	 * 计算订单运费
	 * @param shoppingcartIds
	 * @return
	 */
	private BigDecimal calucateDelvieryFee(List<String> shoppingcartIds , String deliveryAddressId , String deliveryType, String deliveryFeePayType){
		// 运费
		BigDecimal lastDeliveryFee = new BigDecimal(0);
		// 重新计算订单运费
		// 查询结算商品的默认运费，sql直接计算出整个订单商品的默认普通运费多少 ，快递物流运费多少，其它运费多少
		Map<String, Object> dparam = new HashMap<String, Object>();
		dparam.put("shoppingcartIdsList", shoppingcartIds);
		ProductEntity deliveryFee = productService.listShoppingcartProductDelivery(dparam);

		// deliveryAddressId
		// deliveryType
		// deliveryFeePayType

		// 普通物流运费
		BigDecimal normalDeliveryFee = deliveryFee.getNormalDeliveryFee();
		// 快递物流运费
		BigDecimal expressDeliveryFee = deliveryFee.getExpressDeliveryFee();
		// 其它物流运费
		BigDecimal otherDeliveryFee = deliveryFee.getOtherDeliveryFee();
		
		// 获取公司减免地址信息
		dparam.clear();
		dparam.put("companyId", getCompany().getId());
		List<CompanyExpressConfigEntity> freeAddressList = companyExpressConfigService.listCompanyExpressConfig(dparam);
		String normalDeliveryAddressIds = "";
		String expressDeliveryAddressIds = "";
		if (freeAddressList != null && freeAddressList.size() > 0) {
			for (CompanyExpressConfigEntity config : freeAddressList) {
				if (config.getExpressType() == 1) {
					normalDeliveryAddressIds = config.getAddressIdsStr();
				} else if (config.getExpressType() == 2) {
					normalDeliveryAddressIds = "all";
				} else if (config.getExpressType() == 3) {
					expressDeliveryAddressIds = config.getAddressIdsStr();
				} else if (config.getExpressType() == 4) {
					expressDeliveryAddressIds = "all";
				}
			}
		}
		
		if("02".equals(deliveryFeePayType)){
			// 到付运费为0
			return new BigDecimal(0);
		}
		
		if("1".equals(deliveryType)){
			// 客户自提
			lastDeliveryFee = new BigDecimal(0);
		}else if("2".equals(deliveryType)){
			// 普通物流 
			if("all".equals(normalDeliveryAddressIds)){
				lastDeliveryFee = new BigDecimal(0);
			}else{
				if(isFee(deliveryAddressId, normalDeliveryAddressIds)){
					lastDeliveryFee = new BigDecimal(0);
				}else{
					lastDeliveryFee = normalDeliveryFee;
				}
			}
		}else if("3".equals(deliveryType)){
			// 快递物流 
			if("all".equals(expressDeliveryAddressIds)){
				lastDeliveryFee = new BigDecimal(0);
			}else{
				if(isFee(deliveryAddressId, expressDeliveryAddressIds)){
					lastDeliveryFee = new BigDecimal(0);
				}else{
					lastDeliveryFee = expressDeliveryFee;
				}
			}
		}else if("4".equals(deliveryType)){
			lastDeliveryFee = otherDeliveryFee;
		}
		return lastDeliveryFee;
	}
	
	/**
	 * 判断物流地址是否在免费地址列表中
	 * @param deliveryAddressId
	 * @param deliveryAddressIds
	 * @return
	 */
	private boolean isFee(String deliveryAddressId, String deliveryAddressIds){
		boolean flag = false;
		if(StringUtil.isNotEmpty(deliveryAddressIds)){
			String[] addressIdArr = deliveryAddressIds.split(",");
			for (String addressId : addressIdArr) {
				if(deliveryAddressId.equals(addressId)){
					flag = true;
					break;
				}
			}
		}else{
			flag = false;
		}
		return flag;
	}
	
	/**
	 * 订单提交成功，跳转到支付页面
	 * @param request
	 * @return
	 */
	@RequestMapping("toOrderPay")
	public String toPay(HttpServletRequest request){
		String orderCode = request.getParameter("orderCode");
		request.setAttribute("orderCode", orderCode);
		// 从我的订单页面跳转过来的没有收货信息和付款金额  
		// 必须重新查询订单
		
		Map<String, Object> param = new HashMap<>();
		param.put("orderCode", orderCode);
		List<OrderEntity> orderList = orderService.listOrder(param);
		OrderEntity order = null;
		if(orderList != null && orderList.size() > 0){
			order = orderList.get(0);
		}
		request.setAttribute("deliveryAddress", order.getProvinceName()+order.getCityName()+order.getAreaName()+order.getStreetName()+order.getStreetName());
		request.setAttribute("receiverName", order.getReceiverName());
		request.setAttribute("receiverMobile", order.getReceiverMobile());
		request.setAttribute("realPayMoney", order.getRealPayMoney());
		
		/**
		if(StringUtil.isEmpty(realPayMoney)){
			// 从我的订单页面跳转过来的没有收货信息和付款金额  
			// 查询订单
			OrderEntity order = orderService.getOrderByCode(orderCode);
			request.setAttribute("deliveryAddress", order.getProvinceName()+order.getCityName()+order.getAreaName()+order.getStreetName()+order.getStreetName());
			request.setAttribute("receiverName", order.getReceiverName());
			request.setAttribute("receiverMobile", order.getReceiverMobile());
			request.setAttribute("realPayMoney", order.getRealPayMoney());
		}else{
			String deliveryAddress = request.getParameter("deliveryAddress");
			String receiverName = request.getParameter("receiverName");
			String receiverMobile = request.getParameter("receiverMobile");
			String realPayMoney = request.getParameter("realPayMoney");
			// 提交订单后直接跳转的支付页面(相关信息可以带过来)
			request.setAttribute("deliveryAddress", deliveryAddress);
			request.setAttribute("receiverName", receiverName);
			request.setAttribute("receiverMobile", receiverMobile);
			request.setAttribute("realPayMoney", realPayMoney);
		}
		*/
		// 查询银行账号
		param.clear();
		param.put("status", 1);
		List<SysPayConfigEntity> payAccountList = sysPayConfigService.listSysPayConfig(param);
		//查询已上传的支付凭证
		param.put("orderCode", orderCode);
		param.put("isDelete", 0);
		request.setAttribute("payAccountList", payAccountList);
		
		return "pc/order/order_pay";
	}
	
	
	/**
	 * 订单提交成功，跳转调价提示页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/toOrderAdjustPage")
	public String toOrderAdjustPage(HttpServletRequest request){
		String orderCode = request.getParameter("orderCode");
		request.setAttribute("orderCode", orderCode);
		// 从我的订单页面跳转过来的没有收货信息和付款金额  
		// 必须重新查询订单
		
		Map<String, Object> param = new HashMap<>();
		param.put("orderCode", orderCode);
		List<OrderEntity> orderList = orderService.listOrder(param);
		OrderEntity order = null;
		if(orderList != null && orderList.size() > 0){
			order = orderList.get(0);
		}
		request.setAttribute("deliveryAddress", order.getProvinceName()+order.getCityName()+order.getAreaName()+order.getStreetName()+order.getStreetName());
		request.setAttribute("receiverName", order.getReceiverName());
		request.setAttribute("receiverMobile", order.getReceiverMobile());
		request.setAttribute("realPayMoney", order.getRealPayMoney());
		request.setAttribute("order", order);
		return "pc/order/adjust_result";
	}
	
	
	/**
	 * 对公账户支付
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2017年11月21日 下午4:31:09
	 */
	@RequestMapping("/publicPay")
	public String publicPay(HttpServletRequest request) {
		String orderCode = request.getParameter("orderCode");
		Long sysConfigPayId = Long.parseLong(request.getParameter("accountId"));
		String imgPath = request.getParameter("imgPath");

		OrderEntity order = orderService.getOrderByCode(orderCode);
		SysPayConfigEntity payAccount = sysPayConfigService.getSysPayConfigById(sysConfigPayId);
		OrderPayEntity orderPay = new OrderPayEntity();
		orderPay.setOrderCode(orderCode);
		
		String currentUserCode = getUserCode();
		// 支付流水号   1位下单渠道+时间戳后8位+用户登录名后4位
		String payCode = "P"+String.valueOf(System.currentTimeMillis()).substring(3)
						+currentUserCode.substring(currentUserCode.length()-4);
		orderPay.setPayCode(payCode);
		orderPay.setPayTime(new Date());
		orderPay.setPayMoney(order.getRealPayMoney());
		orderPay.setPayType(OrderConstants.ORDER_PAY_TYPE.PUBLIC_BANK_PAY.getCode());
		orderPay.setFilePath(imgPath);
		orderPay.setAccountName(payAccount.getAccountName());
		orderPay.setBankAccount(payAccount.getBankAccount());
		orderPay.setBankName(payAccount.getBankName());
		orderPay.setOpenBank(payAccount.getBankChild());
		orderPay.setConfirmStatus(OrderConstants.ORDER_PAY_CONFIRM_STATUS.NOT_CONFIRM.getCode());
		orderPay.setCreater(getUserCode());
		
		//修改订单状态(立即付款进入待审核，货到付款进入待核销)
		if (ORDER_PAY_MODEL.PAY_DELIVERY.getCode().equals(order.getPayModel())) {
			order.setOrderStatus(OrderConstants.ORDER_STATUS.WAIT_TO_CHECK.getCode());
			order.setOrderStatusName(OrderConstants.ORDER_STATUS.WAIT_TO_CHECK.getName());
		} else if (ORDER_PAY_MODEL.PAY_NOW.getCode().equals(order.getPayModel())) {
			order.setOrderStatus(OrderConstants.ORDER_STATUS.WAIT_TO_APPROVE.getCode());
			order.setOrderStatusName(OrderConstants.ORDER_STATUS.WAIT_TO_APPROVE.getName());
		} else {
			return "pc/order/pay_error";
		}
		
		order.setPayType(OrderConstants.ORDER_PAY_TYPE.PUBLIC_BANK_PAY.getCode());
		order.setPayTypeName(OrderConstants.ORDER_PAY_TYPE.PUBLIC_BANK_PAY.getName());
		order.setPayTime(new Date());
		order.setModifier(getUserName());
		order.setPayStatus(OrderConstants.ORDER_PAY_STATUS.PAYED.getCode());
		
		//记录日志
		OrderLogEntity orderLog = new OrderLogEntity();
		orderLog.setOrderCode(order.getOrderCode());
		orderLog.setOperaterCode(getUserCode());
		orderLog.setOperaterName(getUserName());
		orderLog.setOpTime(new Date());
//		orderLog.setLogType(logType);
		orderLog.setLogContent("支付订单成功");
		orderLog.setCreater(getUserName());
		
		orderService.commitOrderPay(order, orderPay, orderLog);
		
		request.setAttribute("order", order);
		return "pc/order/pay_result";
	}
	
	/**
	 * 对私人银行卡支付
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2017年11月21日 下午4:31:09
	 */
	@RequestMapping("/privatePay")
	public String privatePay(HttpServletRequest request) {
		String orderCode = request.getParameter("orderCode");
		Long sysConfigPayId = Long.parseLong(request.getParameter("accountId"));
		String imgPath = request.getParameter("imgPath");

		OrderEntity order = orderService.getOrderByCode(orderCode);
		SysPayConfigEntity payAccount = sysPayConfigService.getSysPayConfigById(sysConfigPayId);
		OrderPayEntity orderPay = new OrderPayEntity();
		orderPay.setOrderCode(orderCode);
		String currentUserCode = getUserCode();
		// 支付流水号   1位下单渠道+时间戳后8位+用户登录名后4位
		String payCode = "P"+String.valueOf(System.currentTimeMillis()).substring(3)
						+currentUserCode.substring(currentUserCode.length()-4);
		orderPay.setPayCode(payCode);
		orderPay.setPayTime(new Date());
		orderPay.setPayMoney(order.getRealPayMoney());
		orderPay.setPayType(OrderConstants.ORDER_PAY_TYPE.PRIVATE_BANK_PAY.getCode());
		orderPay.setFilePath(imgPath);
		orderPay.setAccountName(payAccount.getAccountName());
		orderPay.setBankAccount(payAccount.getBankAccount());
		orderPay.setBankName(payAccount.getBankName());
		orderPay.setOpenBank(payAccount.getBankChild());
		orderPay.setConfirmStatus(OrderConstants.ORDER_CONTRACT_STATUS.NOT_CONFIRM.getCode());
		orderPay.setCreater(getUserCode());
		
		//修改订单状态(立即付款进入待审核，货到付款进入待核销)
		if (ORDER_PAY_MODEL.PAY_DELIVERY.getCode().equals(order.getPayModel())) {
			order.setOrderStatus(OrderConstants.ORDER_STATUS.WAIT_TO_CHECK.getCode());
			order.setOrderStatusName(OrderConstants.ORDER_STATUS.WAIT_TO_CHECK.getName());
		} else if (ORDER_PAY_MODEL.PAY_NOW.getCode().equals(order.getPayModel())) {
			order.setOrderStatus(OrderConstants.ORDER_STATUS.WAIT_TO_APPROVE.getCode());
			order.setOrderStatusName(OrderConstants.ORDER_STATUS.WAIT_TO_APPROVE.getName());
		} else {
			return "pc/order/pay_error";
		}
		order.setPayType(OrderConstants.ORDER_PAY_TYPE.PRIVATE_BANK_PAY.getCode());
		order.setPayTypeName(OrderConstants.ORDER_PAY_TYPE.PRIVATE_BANK_PAY.getName());
		order.setPayTime(new Date());
		order.setPayStatus(OrderConstants.ORDER_PAY_STATUS.PAYED.getCode());
		order.setModifier(getUserName());
		
		//记录日志
		OrderLogEntity orderLog = new OrderLogEntity();
		orderLog.setOrderCode(order.getOrderCode());
		orderLog.setOperaterCode(getUserCode());
		orderLog.setOperaterName(getUserName());
		orderLog.setOpTime(new Date());
//		orderLog.setLogType(logType);
		orderLog.setLogContent("支付订单成功");
		orderLog.setCreater(getUserName());
		
		orderService.commitOrderPay(order, orderPay, orderLog);
		
		request.setAttribute("order", order);
		return "pc/order/pay_result";
	}
	
	
	

	/**
	 * 取消订单
	 * @param request 请求对象
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/cancelOrder")
	public String cancelOrder(HttpServletRequest request){
		// 订单号
		String orderCode = request.getParameter("orderCode");
		try {
			Map<String, Object> param = new HashMap<String , Object>();
			param.put("orderCode", orderCode);
			param.put("orderStatus", OrderConstants.ORDER_STATUS.CANCELED.getCode());
			param.put("cancelTime", new Date());
			param.put("cancelReason", request.getParameter("cancelReason"));
			param.put("modifier", getUserName());
			
			int result = orderService.cancelOrder(param);
		} catch (Exception e) {
			handleException("取消订单错误", logger, e);
		}
		return "redirect:/pc/order/list";
	}
	
	/**
	 * 跳转打印合同页面
	 * @param request 请求对象
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/toPrintOrderContract")
	public String toPrintOrderContract(HttpServletRequest request){
		// 订单号
		String orderCode = request.getParameter("orderCode");
		// 商品编码
		List<String>  productCodeList = new ArrayList<String>();
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("orderCode", orderCode);
			List<OrderEntity> orderList = orderService.listOrder(params);
			OrderEntity order = orderList.get(0);
			// 提取订单详情商品列表
			String productDetail = order.getProductDetail();
			List<OrderDetailEntity> orderDetailList = null;
			if(StringUtil.isNotEmpty(productDetail)){
				// 将商品详情json串转化为 OrderDetailEntity 列表
				String productDetailJsonStr = "["+productDetail+"]";
				orderDetailList = JSONArray.parseArray(productDetailJsonStr, OrderDetailEntity.class);
				// 商品详情中的规格项
				if(orderDetailList != null && orderDetailList.size() > 0){
					for (OrderDetailEntity detail : orderDetailList) {
						productCodeList.add(detail.getProductCode());
						// 计算小计
						detail.setSubTotalItemMoney(detail.getProductAdjustPrice().multiply(new BigDecimal(detail.getBuyNum())));
						// 提取规格项
						if(StringUtil.isNotEmpty(detail.getProductSpec())){
							List<ProductSpecEntity> specList = JSONArray.parseArray(detail.getProductSpec(),ProductSpecEntity.class);
							detail.setProductSpecList(specList);
						}
					}
				}
				request.setAttribute("orderDetailList", orderDetailList);
			}
			
			Map<String, ProductEntity>  productMap = new HashMap<String, ProductEntity>();
			if(productCodeList != null && productCodeList.size() > 0){
				params.clear();
				params.put("productCodeList", productCodeList);
				List<ProductEntity>  productList = productService.listProductForContract(params);
				if(productList != null && productList.size() > 0){
					for (ProductEntity product : productList) {
						productMap.put(product.getProductCode(), product);
					}
				}
			}
			
			if(orderDetailList != null && orderDetailList.size() > 0){
				for (OrderDetailEntity detail : orderDetailList) {
					if(productMap.containsKey(detail.getProductCode())){
						ProductEntity product = productMap.get(detail.getProductCode());
						detail.setProductCategoryName(product.getProductCategoryName());
						detail.setProductSalesUnitName(product.getProductSalesUnitName());
					}
				}
			}
			// 订单信息
			request.setAttribute("order", order);
			// 订单人工高价  订单调价 + 商品调价
			request.setAttribute("adjustPriceMoney", order.getAdjustOrderMoney().add(order.getAdjustProductMoney()));
			// 实付金额大写
			request.setAttribute("realPayMoney", NumberToCN.number2CNMontrayUnit(order.getRealPayMoney()));
			request.setAttribute("currentDate", DateUtils.formatDate(new Date(), null));
			
			// 查询合同甲方代表人信息
			/*params.clear();
			params.put("companyId", getCompany().getId());
			CustomerEntity customer = customerService.listContractCustomer(params);*/
			CustomerEntity customer = this.getCustomer();
			request.setAttribute("customer", customer);
			
			// 账期
			CompanyEntity company = getCompany();
			String paymentDays = company.getPaymentDays();
			if(StringUtil.isEmpty(paymentDays)){
				paymentDays = "10";
			}
			request.setAttribute("paymentDays", paymentDays);
		} catch (Exception e) {
			handleException("跳转打印合同页面", logger, e);
		}
		return "/pc/order/order_contract_download";
	}
	
	
	/**
	 * 跳转上传合同页面
	 * @param request 请求对象
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/toUploadOrderContract")
	public String toUploadContract(HttpServletRequest request){
		// 订单号
		String orderCode = request.getParameter("orderCode");
		try {
			OrderEntity order = orderService.getOrderByCode(orderCode);
			request.setAttribute("realPayMoney", order.getRealPayMoney());
			request.setAttribute("orderCode", orderCode);
			
			// 查询订单付款信息
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("orderCode", orderCode);
			List<OrderContractEntity> contractList = orderContractService.listOrderContract(param);
			request.setAttribute("contractList", contractList);
						
		} catch (Exception e) {
			handleException("跳转上传合同页面", logger, e);
		}
		return "/pc/order/order_upload_contract";
	}
	
	/**
	 * 上传订单合同
	 * @param request 请求对象
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/uploadOrderContract")
	@ResponseBody
	public Map<String, Object> uploadOrderContract(HttpServletRequest request){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 订单号
		String orderCode = request.getParameter("orderCode");
		String contractImagePath = request.getParameter("contractImagePath");
		String intro = request.getParameter("intro");
		String approveResult = request.getParameter("approveResult");
		String contractId = request.getParameter("contractId");
		try {
			Map<String, Object> param = new HashMap<String , Object>();
			param.put("orderCode", orderCode);
			// 上传订单合同后，订单状态修改为待审核
			param.put("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_APPROVE.getCode());
			param.put("contractImagePath", contractImagePath);
			param.put("approveResult", approveResult);
			param.put("uploadContractTime", new Date());
			param.put("intro", intro);
			param.put("creater", getUserName());
			param.put("modifier", getUserName());
			param.put("contractId", contractId);
			
			//记录日志
			OrderLogEntity orderLog = new OrderLogEntity();
			orderLog.setOrderCode(orderCode);
			orderLog.setOperaterCode(getUserCode());
			orderLog.setOperaterName(getUserName());
			orderLog.setOpTime(new Date());
//			orderLog.setLogType(logType);
			orderLog.setLogContent("提交合同凭证成功");
			orderLog.setCreater(getUserName());
			param.put("orderLogEntity", orderLog);
			
			int result = orderService.uploadOrderContract(param);
			resultMap.put("resultCode", result>0?"1":"0");
			resultMap.put("resultMsg", result>0?"操作成功":"操作失败");
		} catch (Exception e) {
			handleException("上传订单合同", logger, e);
			resultMap.put("code", "0");
			resultMap.put("resultMsg", "操作失败");
		}
		return resultMap;
	}
	
	
	/**
	 * 跳转重新上传付款凭证页面
	 * @param request 请求对象
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/toReuploadOrderPayVoucher")
	public String toReuploadOrderPayVoucher(HttpServletRequest request){
		// 订单号
		String orderCode = request.getParameter("orderCode");
		try {
			// 查询订单信息
			OrderEntity order = orderService.getOrderByCode(orderCode);
			request.setAttribute("realPayMoney", order.getRealPayMoney());
			request.setAttribute("orderCode", orderCode);
			// 查询订单付款信息
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("orderCode", orderCode);
			List<OrderContractEntity> contractList = orderContractService.listOrderContract(param);
			request.setAttribute("contractList", contractList);
		} catch (Exception e) {
			handleException("跳转重新上传付款凭证页面", logger, e);
		}
		return "/pc/order/order_reupload_pay_voucher";
	}
	
	/**
	 * 跳转确认收货(签收)页面
	 * @param request 请求对象
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/toConfirmSign")
	@ResponseBody
	public Map<String, Object> toConfirmSign(HttpServletRequest request){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 订单号
		String orderCode = request.getParameter("orderCode");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("orderCode", orderCode);
		try {
			// 查询订单
			Map<Long, OrderDetailEntity>  productMap = new HashMap<Long, OrderDetailEntity>();
			OrderEntity order = null;
			List<OrderEntity> orderList = orderService.listOrder(paramMap);
			if (orderList != null && orderList.size() > 0) {
				order = orderList.get(0);
				if (StringUtil.isNotEmpty(order.getProductDetail())) {
					List<OrderDetailEntity> productList = JSONArray.parseArray(
							"[" + order.getProductDetail() + "]",
							OrderDetailEntity.class);
					order.setProductList(productList);
					for (OrderDetailEntity product : productList) {
						productMap.put(product.getId(), product);
					}
				}
			}
			request.setAttribute("order", order);
				
			// 查询已发货的商品清单
			List<OrderDeliveredBillEntity> deliveredList = orderDeliveredBillService.listOrderDetailDelivered(paramMap);
			if(deliveredList != null && deliveredList.size() > 0 ){
				for (OrderDeliveredBillEntity product : deliveredList) {
					// 订单状态 
					product.setOrderStatus(order.getOrderStatus());
					if(StringUtil.isNotEmpty(product.getDeliveredProductDetails())){
						// 发货商品详情
						List<OrderProductDeliveredEntity>  productList = JSONArray.parseArray("["+product.getDeliveredProductDetails()+"]", OrderProductDeliveredEntity.class);
						List<OrderDetailEntity>  detailList = new ArrayList<OrderDetailEntity>();
						if(productList != null && productList.size() > 0){
							for (OrderProductDeliveredEntity delivredProduct : productList) {
								OrderDetailEntity  tmpDetail = productMap.get(delivredProduct.getDetailId());
								OrderDetailEntity detail = new OrderDetailEntity();
								BeanUtils.copyProperties(detail, tmpDetail);
								
								if(StringUtil.isNotEmpty(detail.getProductSpec())){
									List<ProductSpecEntity> productSpecList = JSONArray.parseArray(detail.getProductSpec(), ProductSpecEntity.class);;
									detail.setProductSpecList(productSpecList);
								}
								
								detail.setSendNum(delivredProduct.getDeliveredNum());
								detailList.add(detail);
							}
						}
						product.setDeliveredProductList(detailList);
					}
				}
			}
			// 签收页面按显示待签收的物流单，及详情
			request.setAttribute("deliveredList", deliveredList);
			resultMap.put("order", order);
			resultMap.put("deliveredList", deliveredList);
			resultMap.put("resultCode","1");
			resultMap.put("resultMsg", "操作成功");
		} catch (Exception e) {
			handleException("查询发货单失败", logger, e);
			resultMap.put("code", "0");
			resultMap.put("resultMsg", "操作失败");
		}
		return resultMap;
	}
	
	/**
	 * 确认收货
	 * @param request 请求对象
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/confirmSign")
	@ResponseBody
	public Map<String, Object> confrimSign(HttpServletRequest request){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 订单号
		String orderCode = request.getParameter("orderCode");
		String deliveryCode = request.getParameter("deliveryCode");
		String deliveryBillId = request.getParameter("deliveryBillId");
		try {
			Map<String, Object> param = new HashMap<String , Object>();
			param.put("orderCode", orderCode);
			// 签收订单，检查是否发货完成，发货完成则修改订单状态 
			param.put("deliveryCode", deliveryCode);
			param.put("deliveryBillId", deliveryBillId);
			param.put("signTime", new Date());
			param.put("signStatus", OrderConstants.ORDER_SIGN_STATUS.SIGNED.getCode());
			param.put("signName", getUserName());
			param.put("modifier", getUserName());
			
			//记录日志
			OrderLogEntity orderLog = new OrderLogEntity();
			orderLog.setOrderCode(orderCode);
			orderLog.setOperaterCode(getUserCode());
			orderLog.setOperaterName(getUserName());
			orderLog.setOpTime(new Date());
//			orderLog.setLogType(logType);
			orderLog.setLogContent("订单已签收");
			orderLog.setCreater(getUserName());
			param.put("orderLogEntity", orderLog);
			
			// 签收部分发货单
			int result = orderService.signHalfOrder(param);
			resultMap.put("resultCode", result>0?"1":"0");
			resultMap.put("resultMsg", result>0?"操作成功":"操作失败");
		} catch (Exception e) {
			handleException("取消订单错误", logger, e);
			resultMap.put("code", "0");
			resultMap.put("resultMsg", "操作失败");
		}
		return resultMap;
	}

	/**
	 * 检查订单是否支付
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年1月19日 上午9:35:49
	 */
	@RequestMapping("/isOrderPayed")
	@ResponseBody
	public Map<String, Object> isOrderPayed(HttpServletRequest request){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 订单号
		String orderCode = request.getParameter("orderCode");
		try {
			OrderEntity order = orderService.getOrderByCode(orderCode);
			if (OrderConstants.ORDER_PAY_STATUS.PAYED.getCode().equals(order.getPayStatus()) && !OrderConstants.ORDER_STATUS.APPROVE_REJECTED.getCode().equals(order.getOrderStatus()) ) {
				resultMap.put("code", "1");
				resultMap.put("resultMsg", "已支付");
			} else {
				resultMap.put("code", "0");
				resultMap.put("resultMsg", "未支付");
			}
		} catch (Exception e) {
			handleException("获取订单失败", logger, e);
			resultMap.put("code", "0");
			resultMap.put("resultMsg", "操作失败");
		}
		return resultMap;
	}

	/**
	 * 支付成功
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年1月19日 上午9:50:49
	 */
	@RequestMapping("/paySuccess")
	public String paySuccess(HttpServletRequest request) {
		// 订单号
		String orderCode = request.getParameter("orderCode");
		try {
			OrderEntity order = orderService.getOrderByCode(orderCode);
			request.setAttribute("order", order);
			return "pc/order/pay_result";
		} catch (Exception e) {
			handleException("获取订单失败", logger, e);
		}
		return "pc/order/pay_error";
	}
}
